package com.lyt.robotocr

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import com.ainirobot.coreservice.client.ApiListener
import com.ainirobot.coreservice.client.Definition
import com.ainirobot.coreservice.client.RobotApi
import com.ainirobot.coreservice.client.listener.CommandListener
import com.ainirobot.coreservice.client.listener.Person
import com.ainirobot.coreservice.client.listener.PersonInfoListener
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.lyt.robotocr.config.Config
import com.lyt.robotocr.http.ApiManager
import com.lyt.robotocr.http.PersonInfo
import com.lyt.robotocr.http.RespData
import com.lyt.robotocr.model.CallNumberModel
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_manual.*
import kotlinx.android.synthetic.main.layout_state.*
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.File
import java.util.concurrent.TimeUnit


class MainActivity : BaseActivity() {
    private var handler: Handler? = null
    private var getCoding = false
    private val spinList = mutableListOf("身份证", "银行卡")
    private var facePath = ""
    private var currType = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils.setStatusBarVisibility(window, false)
        setContentView(R.layout.activity_main)
        checkPermission {
            init()
        }
    }

    private val personInfoListener = object : PersonInfoListener() {
        override fun onData(code: Int, data: MutableList<Person>?) {
            super.onData(code, data)
            //  拿到人脸数据ID
            if (data == null || data.size == 0) {
                println("【IM】MainActivity 拿到的人脸信息中的人员ID为 null,此时照片也没有获取到 showManualTakeNum")
                showManualTakeNum()
                return
            }
            val faceID = data[0].id
            RobotApi.getInstance().getPictureById(reqId, faceID, 1, object : CommandListener() {
                override fun onResult(result: Int, message: String?) {
                    super.onResult(result, message)
                    //  人脸获取成功  1 {"pictures":["/storage/emulated/0/robot/cache/picture/face_33_2020-12-04-17:01:15_8_1t.jpg"],"status":"ok"}
                    println(("人脸获取成功  $result $message"))
                    if (TextUtils.isEmpty(message)) {
                        println(("没有人脸 showManualTakeNum "))
                        showManualTakeNum()
                        return
                    }
                    message?.let {
                        val json = JSONObject(it)
                        when (json.optString("status")) {
                            Definition.RESPONSE_OK -> {
                                val pictures = json.optJSONArray("pictures")
                                pictures?.let { arr ->
                                    if (!TextUtils.isEmpty(arr.optString(0))) {
                                        //  到这里才能真正取到用户照片 path 还不能为空的前提下
                                        val path = arr.optString(0)
                                        facePath = path
                                        val nameList = mutableListOf<String>()
                                        nameList.add(path)
                                        println("【IM】MainActivity  onResult: 进行 getPersonInfoFromNet")
                                        getPersonInfoFromNet(faceID.toString(), nameList)
                                    }
                                }
                            }
                            else -> {
                                println(
                                    "【IM】MainActivity showManualTakeNum onResult: ${json.optString(
                                        "status"
                                    )}"
                                )
                                showManualTakeNum()
                            }
                        }
                    }

                }

                override fun onError(errorCode: Int, errorString: String?) {
                    super.onError(errorCode, errorString)
                    println("【IM】MainActivity 获取照片失败 showManualTakeNum errorCode = $errorCode errorString = $errorString")
                    showManualTakeNum()
                }
            })
            handler?.sendEmptyMessage(10086)
        }
    }

    private fun showError(t: RespData<CallNumberModel>) {
        layoutState.visibility = View.VISIBLE
        successView.visibility = View.GONE
        loadingView.visibility = View.GONE
        addressOrFailTv.text = "取号失败"
        tipOrFailReasonTv.text = "对不起找不到您的身份信息，请您到叫号机进行排队叫号，谢谢"

        Observable.interval(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(object : Observer<Long> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: Long) {
                    val str = 10 - t
                    if (str <= 0) {
                        finish()
                    } else {
                        counterTv.text = str.toString()
                    }

                }

                override fun onError(e: Throwable) {
                }
            })
    }

    /**
     * 拿人脸信息
     */
    private fun getPersonInfoFromNet(personID: String, nameList: List<String>) {
        RobotApi.getInstance().getPersonInfoFromNet(
            reqId,
            personID,
            nameList,
            object : CommandListener() {
                override fun onResult(
                    result: Int,
                    message: String?
                ) {
                    super.onResult(result, message)
                    println("【IM】MainActivity getPersonInfoFromNet onResult 得到结果 $result    message = $message")
                    if (result == 1) {
                        val person = GsonUtils.fromJson(
                            message,
                            PersonInfo::class.java
                        )
                        if (getCoding) {
                            println("【IM】MainActivity 多次取号 return")
                            return
                        }
                        takeNum(person.data.people.user_id)
                    } else {
                        println("【IM】MainActivity  onResult: 164 拿人脸信息失败")
                        showManualTakeNum()
                    }
                }

                override fun onError(
                    errorCode: Int,
                    errorString: String?
                ) {
                    super.onError(errorCode, errorString)
                    showManualTakeNum()
                    println("【IM】MainActivity 错误 $errorCode     $errorString")
                }
            })
    }

    /**
     * 取号核心方法
     * reqId
     */
    private fun takeNum(reqId: String) {
        MainScope().launch {
            try {
                println("【IM】MainActivity 取号开始  reqId号码为  = $reqId")
                getCoding = true
                ApiManager.getApi(Config.BASE_URL).callNumber(reqId).apply {
                    if (success()) {
                        println("【IM】MainActivity 取号成功 号码 : ${data.queCustNo} 等待人数 ${data.preWaitNo}")
                        showSuccess(data)
                    } else {
                        println("【IM】MainActivity 取号失败 retCode : $retCode retMsg $retMsg")
                        showError(this)
                    }
                }
            } catch (e: Throwable) {
                println("【IM】MainActivity 取号失败 Throwable : ${e.message}")
                showError(
                    RespData(
                        "-1",
                        "取号失败,请稍后再试",
                        CallNumberModel(
                            "",
                            "",
                            ""
                        )
                    )
                )
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showSuccess(data: CallNumberModel) {
        loadingView.visibility = View.GONE
        addressOrFailTv.text = "济南市中支行"
        address1Tv.text = "经十路21586号"
        numberTv.text = data.queCustNo
        waitNumTv.text = data.preWaitNo
        stateTv.text = "取号成功"
        tipOrFailReasonTv.text = "请在休息区等待叫号，请注意关注叫号机广播。"
        layoutState.visibility = View.VISIBLE
        loadingView.visibility = View.GONE
        successView.visibility = View.VISIBLE
        Observable.interval(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(object : Observer<Long> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: Long) {
                    val str = 10 - t
                    if (str <= 0) {
                        finish()
                    } else {
                        counterTv.text = str.toString()
                    }

                }

                override fun onError(e: Throwable) {
                }
            })
    }

    /**
     * 手动取号
     */
    private fun showManualTakeNum() {
        println("【IM】MainActivity  showManualTakeNum:layoutManual.visibility == View.GONE ? ${layoutManual.visibility == View.GONE}")
        if (layoutManual.visibility == View.GONE) {
            layoutState.visibility = View.GONE
            loadingView.visibility = View.GONE
            layoutManual.visibility = View.VISIBLE
            if (!TextUtils.isEmpty(facePath)) {
                println("【IM】MainActivity  showManualTakeNum&facePath $facePath")
                //  uploadFile()
            }
        }
    }


    private var reqId = -1

    var disposable: Disposable? = null
    private fun init() {
        getCoding = false
        @SuppressLint("HandlerLeak")
        handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                if (msg.what == 10086) {
                    println("【IM】MainActivity 人脸识别停止!")
                    RobotApi.getInstance().stopGetAllPersonInfo(reqId, personInfoListener)
                }
            }
        }
        /*=println("【IM】MainActivity init 进入")
        Observable.interval(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(object : Observer<Long> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                    disposable = d
                }

                override fun onNext(t: Long) {
                    if (t > 3 && !getCoding) {
                        finish()
                        return
                    }
                    if (loadingView.visibility == View.GONE) {
                        disposable?.dispose()
                    }

                }

                override fun onError(e: Throwable) {
                }
            })*/

        RobotApi.getInstance().connectServer(this, object : ApiListener {
            override fun handleApiDisabled() {
                println("【IM】MainActivity Server不可用")
            }

            override fun handleApiConnected() {
                println("【IM】MainActivity Server已连接")
                RobotApi.getInstance().startGetAllPersonInfo(10086, personInfoListener)
            }

            override fun handleApiDisconnected() {
                println("【IM】MainActivity Server已断开")
            }
        })
        typeSpinner.attachDataSource(spinList)
        typeSpinner.setOnSpinnerItemSelectedListener { _, _, pos, _ ->
            currType = pos
        }
        toCallNo.setOnClickListener {
            if (TextUtils.isEmpty(userNameEt.text)) {
                ToastUtils.showShort("请输入用户名")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(cardNoEt.text)) {
                ToastUtils.showShort("请输入证件号码")
                return@setOnClickListener
            }
            println("【IM】MainActivity  init:用户输入 ${userNameEt.text} ${cardNoEt.text} $currType")
            ToastUtils.showShort("用户输入 ${userNameEt.text} ${cardNoEt.text} $currType")
        }
    }

    /**
     * 上传文件
     */
    fun uploadFile() {
        val file =
            File(Environment.getExternalStorageDirectory().absolutePath + "/DCIM/Camera/zzz.jpg")
        val requestBody = RequestBody.create(MediaType.parse("image/*"), file)
        val part = MultipartBody.Part.createFormData("image", file.name, requestBody)
        MainScope().launch {
            ApiManager.getApi(Config.BASE_LOCAL).compareFace(part)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable?.dispose()
    }
}

